package com.dm.wallpaper.library.utils;

import com.dm.wallpaper.library.ResourceTable;
import com.dm.wallpaper.library.abilityPackage.WallpaperBoardApplication;
import com.dm.wallpaper.library.customview.LoadingLineView;
import com.dm.wallpaper.library.items.PopupItem;
import com.dm.wallpaper.library.items.Wallpaper;
import com.dm.wallpaper.library.preferences.Preferences;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.PopupDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.image.PixelMap;
import ohos.miscservices.wallpaper.WallpaperController;

import java.util.concurrent.atomic.AtomicBoolean;

import static ohos.miscservices.wallpaper.WallpaperController.WALLPAPER_LOCK;
import static ohos.miscservices.wallpaper.WallpaperController.WALLPAPER_SYSTEM;

/*
 * Copyright (C) 2021 The Chinese Software International Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
public class DialogUtils {
    private static DialogUtils dialogUtils;

    private DialogUtils() {
    }


    public static DialogUtils getInstance() {
        if (dialogUtils == null) {
//            synchronized (DialogUtils.class) {
//                if (dialogUtils == null) {
            dialogUtils = new DialogUtils();
//                }
//            }
        }
        return dialogUtils;
    }

    PopupDialog commonDialog;

    public void showDialog(Component component, Wallpaper wallpaper) {
        showDialog(component, wallpaper, false);
    }

    public void showDialog(Component component, Wallpaper wallpaper, boolean needSaveDevice) {
        if (wallpaper == null) {
            return;
        }
        Component pop_itemlayout = LayoutScatter.getInstance(component.getContext()).parse(ResourceTable.Layout_pop_itemlayout, null, true);
        pop_itemlayout.findComponentById(ResourceTable.Id_save_to_device).setVisibility(needSaveDevice ? Component.INVISIBLE : Component.HIDE);
        pop_itemlayout.setTag(component.getTag());
        Component.ClickedListener clickedListener = new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                commonDialog.destroy();
                AtomicBoolean iscancel = new AtomicBoolean(false);
                Component loading = loadingLaout.initToastLayout(component.getContext());
                PopupDialog popupDialog = showCenterDialog(component.getContext(), loading);
                ((LoadingLineView) loading.findComponentById(ResourceTable.Id_LoadingLine)).startLoading();
                loading.findComponentById(ResourceTable.Id_cancel).setClickedListener(o -> iscancel.set(true));

                try {
                    ImageLoader.getInstance().loadImage(wallpaper.getUrl(), new SimpleImageLoadingListener() {
                        @Override
                        public void onLoadingComplete(String url, Component c, PixelMap pixelMap) {
                            if (pixelMap == null) {
                                Log.i("DialogUtils.onClick([component]):53      暂未获取到此壁纸");
                                return;
                            }
                            if (iscancel.get()) {
                                Toast.show(component.getContext(), "wallpaper apply cancel");
                                return;
                            }
                            Log.i("DialogUtils.onLoadingComplete([url, c, pixelMap]):83");
                            int id = component.getId();
                            if (id == ResourceTable.Id_back) {
                                WallpaperController.getInstance(component.getContext()).setWallpaper(pixelMap, WALLPAPER_SYSTEM);
                            } else if (id == ResourceTable.Id_lock) {
                                WallpaperController.getInstance(component.getContext()).setWallpaper(pixelMap, WALLPAPER_LOCK);
                            } else if (id == ResourceTable.Id_back_and_lock) {
                                WallpaperController.getInstance(component.getContext()).setWallpaper(pixelMap, WALLPAPER_LOCK);
                                WallpaperController.getInstance(component.getContext()).setWallpaper(pixelMap, WALLPAPER_SYSTEM);
                            }
                            popupDialog.destroy();
                            Toast.show(component.getContext(), "wallpaper applied");

                        }

                        @Override
                        public void onLoadingFailed(String s, Component component, FailReason failReason) {
                            super.onLoadingFailed(s, component, failReason);
                            popupDialog.destroy();
                            Toast.show(WallpaperBoardApplication.getInstance(), "wallpaper apply fail");
                        }

                    });

                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
            }
        };
        commonDialog = show(component, pop_itemlayout, clickedListener);
    }

    public PopupDialog show(Component componentShow, Component dialogCompant, Component.ClickedListener clickedListener) {
        Context context = componentShow.getContext();
        PopupDialog commonDialog = new PopupDialog(context, dialogCompant);
        commonDialog.setCustomComponent(dialogCompant);
        if (dialogCompant instanceof ComponentContainer) {
            for (int i = 0; i < ((ComponentContainer) dialogCompant).getChildCount(); i++) {
                ((ComponentContainer) dialogCompant).getComponentAt(i).setClickedListener(clickedListener);
            }
            dialogCompant.setClickedListener(clickedListener);
        } else {
            dialogCompant.setClickedListener(clickedListener);
        }
        commonDialog.setBackColor(Color.TRANSPARENT);
        commonDialog.setAutoClosable(true);
        commonDialog.setTransparent(true);
        int[] local = componentShow.getLocationOnScreen();
        commonDialog.showOnCertainPosition(LayoutAlignment.LEFT | LayoutAlignment.TOP, componentShow.getWidth() + local[0] - 100, componentShow.getHeight() + local[1] - 100);
        return commonDialog;
    }


    public PopupDialog showSortDialog(Context context, Component parent, Component.ClickedListener listener) {
        ComponentContainer dialogSort = (ComponentContainer) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_dialog_sort_list, null, false);
        dialogSort.findComponentById(ResourceTable.Id_image_sort_latest);
        dialogSort.findComponentById(ResourceTable.Id_image_sort_name);
        dialogSort.findComponentById(ResourceTable.Id_image_sort_oldest);
        dialogSort.findComponentById(ResourceTable.Id_image_sort_random);


        Component.ClickedListener mClickedListener = new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (component.getId() == ResourceTable.Id_sort_latest) {
                    Preferences.get().setSortBy(PopupItem.Type.SORT_LATEST);
                } else if (component.getId() == ResourceTable.Id_sort_oldest) {
                    Preferences.get().setSortBy(PopupItem.Type.SORT_OLDEST);
                } else if (component.getId() == ResourceTable.Id_sort_name) {
                    Preferences.get().setSortBy(PopupItem.Type.SORT_NAME);
                } else if (component.getId() == ResourceTable.Id_sort_random) {
                    Preferences.get().setSortBy(PopupItem.Type.SORT_RANDOM);
                }
                listener.onClick(component);
                commonDialog.destroy();
            }
        };


        Text text_sort_random = (Text) dialogSort.findComponentById(ResourceTable.Id_text_sort_random);
        Text text_sort_latest = (Text) dialogSort.findComponentById(ResourceTable.Id_text_sort_latest);
        Text text_sort_name = (Text) dialogSort.findComponentById(ResourceTable.Id_text_sort_name);
        Text text_sort_oldest = (Text) dialogSort.findComponentById(ResourceTable.Id_text_sort_oldest);

        try {
            Color color = new Color(context.getResourceManager().getElement(ResourceTable.Color_green).getColor());
            switch (Preferences.get().getSortBy()) {
                case SORT_OLDEST:
                    text_sort_oldest.setTextColor(color);
                    break;
                case SORT_NAME:
                    text_sort_name.setTextColor(color);
                    break;
                case SORT_LATEST:
                    text_sort_latest.setTextColor(color);
                    break;
                case SORT_RANDOM:
                    text_sort_random.setTextColor(color);
                    break;
            }
        } catch (Exception e) {
        }


        commonDialog = DialogUtils.getInstance().show(parent, dialogSort, mClickedListener);
        return commonDialog;
    }

    PopupDialog popupDialog1;

    public void showToastBottom(Context mContext, Toast.InitToastLayout initToastLayout) {
        Log.i("DialogUtils.showToastBottom([mContext, initToastLayout]):192");
        Component content = initToastLayout.initToastLayout(mContext);
        popupDialog1 = new PopupDialog(mContext, null);
        popupDialog1.setAutoClosable(true);
        popupDialog1.setTransparent(true);
        popupDialog1.setCustomComponent(content);
        popupDialog1.setBackColor(Color.TRANSPARENT);
        popupDialog1.showOnCertainPosition(LayoutAlignment.BOTTOM | LayoutAlignment.HORIZONTAL_CENTER, 0, 0);
        content.setClickedListener(o -> {
            if (popupDialog1.isShowing()) {
                popupDialog1.destroy();
            }
        });
        new EventHandler(EventRunner.getMainEventRunner()).postTask(new Runnable() {
            @Override
            public void run() {
                Log.i("DialogUtils.run([]):204");
                if (popupDialog1.isShowing()) {
                    popupDialog1.destroy();
                }
            }
        }, 2000);
    }

    public PopupDialog showCenterDialog(Context mContext, Component content) {
        Log.i("DialogUtils.showCenterDialog([mContext, initToastLayout]):217");
        PopupDialog popupDialog1 = new PopupDialog(mContext, null);
        popupDialog1.setAutoClosable(true);
        popupDialog1.setTransparent(true);
        popupDialog1.setCustomComponent(content);
        popupDialog1.setBackColor(Color.TRANSPARENT);
        popupDialog1.showOnCertainPosition(LayoutAlignment.CENTER, 0, 0);
        return popupDialog1;
    }

    Toast.InitToastLayout loadingLaout = context -> {
        Component component = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_loading_view, null, false);
        return component;
    };

    public Toast.InitToastLayout getDefaultLoadView() {
        return loadingLaout;
    }
}
